import { createStore } from 'vuex'
import persist from 'vuex-persistedstate'
import { useRouter, useRoute } from 'vue-router'
import { userLogin,userCurrent } from '../utils/api'
interface userList {
  nickName: string
  token: string
  column: string
  email: string
  _id: string
}
export default createStore({
  state: {
    user: <userList>{
      token: '',
      nickName: '',
      _id: "",
      column: ""
    }

  },
  mutations: {
    async changeUser(state, user: userList) {
        state.user.token = user.token
        // 如果登陆成功 有token  请求用户信息
        if (user.token) {
          const response = await userCurrent()          
          const { nickName, column, _id } = response.data
          console.log(nickName,column,);
          state.user.nickName = nickName
          state.user.column = column
          state.user._id = _id
          
        } else {
          console.log(1);
          state.user.nickName = ''
          state.user.column = ''
          state.user._id = ''
        }
     
    }
  },
  actions: {
     login({ commit }, obj) {
         let router = useRouter() 
         userLogin(obj).then((res) => {
          if (res.data.data.token) {
           // console.log(39, res);      
           commit('register', res.data.data)  
          } else {
           return false
          }
        })
        }
      },
        
  modules: {
  },
  plugins:[persist()]
})
